package com.xjh.serverinspect.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据库操作工具类
 * </p>
 *
 * @author xujinghui
 * @since 2024-10-15
 */
public class DatabaseUtils {

    static {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static ConnectionWrapper getConnection(String database, String host, int port, String username, String password) {
        ConnectionWrapper connectionWrapper = new ConnectionWrapper();
        try {
            connectionWrapper.connection = DriverManager.getConnection(String.format("jdbc:postgresql://%s:%d/%s?connectTimeout=10000", host, port, database), username, password);
            connectionWrapper.connected = true;
        } catch (SQLException e) {
            connectionWrapper.connected = false;
            connectionWrapper.connectionError = e.getMessage();
        }
        return connectionWrapper;
    }

    public static List<Map<String, Object>> resultSet2List(ResultSet rs) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            Map<String, Object> row = new HashMap<>();
            for (int i = 1, len = metaData.getColumnCount(); i <= len; i++) {
                row.put(metaData.getColumnName(i), rs.getObject(i));
            }
            list.add(row);
        }
        return list;
    }

    public static ResultItem resultSet2ResultItem(ResultSet rs) throws SQLException {
        ResultItem resultItem = new ResultItem();
        resultItem.setContentType("table");
        resultItem.setTitle("SQL Query Result");
        ResultSetMetaData metaData = rs.getMetaData();
        int len = metaData.getColumnCount();
        List<String[]> rows = new ArrayList<>();
        String[] meta = new String[len];
        int count = 1;
        while (rs.next()) {
            String[] cols = new String[len];
            for (int i = 1; i <= len; i++) {
                cols[i - 1] = rs.getString(i);
            }
            if (count == 1) {
                for (int j = 1; j <= len; j++) {
                    meta[j - 1] = metaData.getColumnName(j);
                }
                count++;
            }
            rows.add(cols);
        }
        resultItem.setMetaData(meta);
        resultItem.setRows(rows);
        return resultItem;
    }

}
